package com.jblv.frame.common.utils;

import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.locks.StampedLock;

/**
 * @author happyonion.yangtao
 * @version 1.0
 * @title RequestHolder
 * @projectName jblv-frame
 * @packageName com.jblv.common.untils
 * @description RequestHolder
 * @date Create at 2020/5/8 14:31
 * @since jdk1.8
 */
public class RequestHolder {
    private static StampedLock lock = new StampedLock();
    public static final String APP_ID = "APP_ID";
    public static final String OPER_USER_ID = "OPER_USER_ID";
    public static final String OPER_USER_NAME = "OPER_USER_NAME";
    public static final String OPER_USER_TYPE = "OPER_USER_TYPE";
    private static final ThreadLocal<Map<String, Object>> requestHolder = new ThreadLocal();

    public RequestHolder() {
    }

    public static void add(Map<String, Object> map) {
        requestHolder.set(map);
    }

    public static Map<String, Object> get() {
        return (Map)requestHolder.get();
    }

    public static Object get(String key) {
        Object returnObj = null;
        Map<String,Object> objMap = requestHolder.get();
        if(objMap == null){
            return null;
        }
        returnObj = objMap.get(key);
        return returnObj;
    }

    public static void remove() {
        requestHolder.remove();
    }

    public static void add(String key, Object value) {
        long stamp = lock.readLock();

        try {
            if (requestHolder.get() == null) {
                requestHolder.set(new HashMap());
            }
        } finally {
            lock.unlock(stamp);
        }

        requestHolder.get().put(key, value);
    }
}
